package com.xywh.micro_warehousing.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xw.repo.XEditText;
import com.xywh.micro_warehousing.R;
import com.xywh.micro_warehousing.di.component.DaggerTab4Component;
import com.xywh.micro_warehousing.di.module.Tab4Module;
import com.xywh.micro_warehousing.mvp.contract.Tab4Contract;
import com.xywh.micro_warehousing.mvp.presenter.Tab4Presenter;
import com.xywh.micro_warehousing.mvp.ui.activity.ScanActivity;
import com.xywh.micro_warehousing.mvp.ui.entity.CounterSave;
import com.xywh.micro_warehousing.mvp.ui.entity.GetFaultCode;
import com.xywh.micro_warehousing.mvp.ui.entity.Tab4;

import org.jetbrains.annotations.NotNull;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import okhttp3.RequestBody;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class Tab4Fragment extends BaseFragment<Tab4Presenter> implements Tab4Contract.View, OnRefreshListener {


    public static final int REQUEST_WU_LIAO = 104;
    @BindView(R.id.xet_container_number)
    XEditText xetContainerNumber;
    @BindView(R.id.niceSpinner)
    NiceSpinner niceSpinner;
    @BindView(R.id.xet_desc)
    XEditText xetDesc;
    @BindView(R.id.img_001)
    ImageView img001;
    @BindView(R.id.rl_img_01)
    RelativeLayout rlImg01;
    @BindView(R.id.img_002)
    ImageView img002;
    @BindView(R.id.rl_img_02)
    RelativeLayout rlImg02;
    @BindView(R.id.img_003)
    ImageView img003;
    @BindView(R.id.rl_img_03)
    RelativeLayout rlImg03;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    private BottomDialogUtil mBottomDialogUtilShare;
    private int imgType = 0;
    private String mImage001 = "";
    private String mImage002 = "";
    private String mImage003 = "";
    private String spid = "";
    private String jiQiMa = "";
    private String mFaultCodeId;
    private boolean isScan = false;

    public static Tab4Fragment newInstance() {
        Tab4Fragment fragment = new Tab4Fragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerTab4Component //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .tab4Module(new Tab4Module(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab4, container, false);
        initToolbar(view);
        return view;
    }

    private void initToolbar(View view) {
        ToolbarUtils.initToolbarTitleNoBack(view, this, "一键报修");
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        PhotoUtil.init(getActivity(), new FrescoIniter());

        mPresenter.getFaultCode(new HashMap<>());


    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)}
     * 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     *
     * <p>
     * Example usage:
     *
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Subscriber(tag = "xetContainerNumber", mode = ThreadMode.MAIN)
    public void setXetContainerNumber(String value) {
        if (!TextUtils.isEmpty(value)) {
            spid = value;
            xetContainerNumber.setText(value);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == REQUEST_WU_LIAO) {
            isScan = false;
            Bundle extras = data.getExtras();
            if (extras != null) {
                String scan_result = extras.getString(BaseConstants.SCAN_RESULT);
                xetContainerNumber.setText(scan_result);
                jiQiMa = scan_result;
                LogUtils.debugEInfo("scan_result=" + scan_result);
            }

        } else {

            if (!isScan) {
                PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
            }
        }
    }

    @Override
    public void getTab4DataSuccess(Tab4 entityData) {


    }

    @Override
    public void getFaultCodeSuccess(List<GetFaultCode> getFaultCodeList) {

        if (getFaultCodeList != null && getFaultCodeList.size() > 0) {
            //getTab4Data();
            ArrayList<String> list = new ArrayList<String>();
//            list.add("RX1251--柜门不能正常开启");
//            list.add("RX1252--库存异常");
//            list.add("RX1253--出库记录异常");
//            list.add("RX1254--入库记录异常");

            for (int i = 0; i < getFaultCodeList.size(); i++) {
                list.add(getFaultCodeList.get(i).getBaseInformationContent());
            }

            mFaultCodeId = String.valueOf(getFaultCodeList.get(0).getBaseInformationId());
            niceSpinner.attachDataSource(list);
            niceSpinner.setGravity(Gravity.LEFT);
            niceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                }
            });
        }
    }

    @Override
    public void counterSaveSuccess(CounterSave entityData) {

        if (entityData != null && entityData.getCode() == 200) {
            showMessage("上报成功");
        } else {
            showMessage("上报失败");
        }
    }

    private void getTab4Data() {
        HashMap<String, String> map = new HashMap<>();
        mPresenter.getTab4Data(map);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

//        mRefreshLayout.finishRefresh();
//        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(getActivity());
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getActivity(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @OnClick({R.id.rl_img_01, R.id.rl_img_02, R.id.rl_img_03, R.id.btn_submit, R.id.xet_container_number})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.xet_container_number:
                toScan();
                break;
            case R.id.rl_img_01:
                xiuGaiTouXiang(img001);
                imgType = 1;
                break;
            case R.id.rl_img_02:
                xiuGaiTouXiang(img002);
                imgType = 2;

                break;
            case R.id.rl_img_03:
                xiuGaiTouXiang(img003);
                imgType = 3;

                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(xetContainerNumber.getText().toString().trim()) || TextUtils.isEmpty(jiQiMa)) {
                    showMessage("请先扫描货柜");
                    toScan();
                    return;
                }
                if (TextUtils.isEmpty(getDesc())) {
                    showMessage("请输入故障描述");
                    return;
                }
                if (!TextUtils.isEmpty(mImage001) || !TextUtils.isEmpty(mImage002) || !TextUtils.isEmpty(mImage003)) {

                } else {
                    showMessage("至少拍一张照片");
                    return;
                }
                String imgStr = "";

                if (!TextUtils.isEmpty(mImage001)) {
                    imgStr += "{\n" +
                            "                \"PictureExtension\": \"jpg\",\n" +
                            "                \"Picture\": \"" + mImage001 + "\"\n" +
                            "            },";
                }
                if (!TextUtils.isEmpty(mImage002)) {
                    imgStr += "{\n" +
                            "                \"PictureExtension\": \"jpg\",\n" +
                            "                \"Picture\": \"" + mImage002 + "\"\n" +
                            "            },";
                }
                if (!TextUtils.isEmpty(mImage003)) {
                    imgStr += "{\n" +
                            "                \"PictureExtension\": \"jpg\",\n" +
                            "                \"Picture\": \"" + mImage003 + "\"\n" +
                            "            },";
                }

                String jsonData = "{\n" +
                        " \"RepFixPictures\": [\n" +
                        ArmsUtils.cutLastString(imgStr) +
                        "        ],\n" +
                        "        \"CounterId\": " + spid + ",\n" +
                        "        \"CounterNo\": " + jiQiMa + ",\n" +
                        "        \"FaultCodeId\": " + mFaultCodeId + ",\n" +
                        "        \"FaultDesc\": \"" + getDesc() + "\"\n" +
                        "}";
                RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData);
                mPresenter.counterSave(body);
                break;
        }
    }

    private void toScan() {
        isScan = true;
        Intent newIntent = new Intent(getActivity(), ScanActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, REQUEST_WU_LIAO);
        this.startActivityForResult(newIntent, REQUEST_WU_LIAO);
    }

    private void xiuGaiTouXiang(ImageView imageView) {
        LinearLayout root = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(Tab4Fragment.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    String imgStr = ArmsUtils.fileToBase64(compressedPath);

                                    if (imgType == 1) {
                                        mImage001 = imgStr;
                                    } else if (imgType == 2) {
                                        mImage002 = imgStr;
                                    } else if (imgType == 3) {
                                        mImage003 = imgStr;
                                    }

                                    Bitmap bitmap = ArmsUtils.base64ToBitmap(imgStr);
                                    imageView.setImageBitmap(bitmap);

                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(Tab4Fragment.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                                LogUtils.debugEInfo("requestCode=" + requestCode);
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {

                                    String imgStr = ArmsUtils.fileToBase64(compressedPath);

                                    if (imgType == 1) {
                                        mImage001 = imgStr;
                                    } else if (imgType == 2) {
                                        mImage002 = imgStr;
                                    } else if (imgType == 3) {
                                        mImage003 = imgStr;
                                    }

                                    Bitmap bitmap = ArmsUtils.base64ToBitmap(imgStr);

                                    imageView.setImageBitmap(bitmap);

                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                                LogUtils.debugEInfo("requestCode=" + requestCode);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                                LogUtils.debugEInfo("requestCode=" + requestCode);

                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(getActivity(), root);
        mBottomDialogUtilShare.showDiaolog();

    }

    @NotNull
    private String getDesc() {
        return xetDesc.getText().toString().trim();
    }

}
